/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package embeddedpaint.user_interface.tools;

import embeddedpaint.EmbeddedPaint;
import embeddedpaint.model.feature.AImageTool;
import embeddedpaint.model.layers.LayerManager;
import embeddedpaint.user_interface.tools.dialog.FrameDrawPen;
import embeddedpaint.user_interface.tools.dialog.ToolFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.JToggleButton;

public class ToolsDrawPen extends AImageTool implements ActionListener, Observer
{

    private static final String M_LABEL_TEXT = "Draw";
    private static final String M_ICON_PATH  = "images/pen.jpg";
    
    private FrameDrawPen        m_frame;

    public ToolsDrawPen (LayerManager imageManager, JFrame application)
    {
        super(imageManager, application);
    }

    @Override
    public String getLabel ()
    {
        return M_LABEL_TEXT;
    }

    @Override
    protected String getIconName ()
    {
        return M_ICON_PATH;
    }

    @Override
    public boolean isToggleButton ()
    {
        return true;
    }

    @Override
    public void actionPerformed (ActionEvent e)
    {
        if (e.getSource() instanceof JToggleButton)
        {
            JToggleButton buton = (JToggleButton) e.getSource();
            
            if (buton.isSelected())
            {
                createObserver();
            }
            else
            {
                removeObservers();
            }
        }
    }

    public void createObserver ()
    {
        m_frame = new FrameDrawPen(m_imageManager, m_application);
        m_frame.addObserver(this);
        
        ((EmbeddedPaint) this.m_application).getM_workspace().drawOn();
        
        this.m_actif = true;

    }

    public void removeObservers ()
    {
        this.m_actif = false;
        
        ((EmbeddedPaint) this.m_application).getM_workspace().drawOff();
        
        if (m_frame != null)
        {
            m_frame = null;
        }
        
        this.setChanged();
        this.notifyObservers();
    }

    @Override
    public void dispose ()
    {
        if (m_frame != null)
        {
            m_frame.removeObserver(this);
            m_frame.dispose();
        }
        
        removeObservers();
    }

    @Override
    public void update (Observable o, Object arg)
    {
        String key = (String) arg;

        if (key.equals(ToolFrame.G_UPDATE_KEY_VALUE_CHANGED))
        {
            ((EmbeddedPaint) this.m_application).getM_workspace().setColorToDraw(m_frame.getM_color());
        }
        else
        {
            removeObservers();
        }
    }
}
